#include "ClientSession.h"
#include "../Server/utMessage.pb.h"
#include "PlayerManager.h"
#include "ScriptManager.h"

using namespace utgame;

ClientSession::ClientSession(struct bufferevent *pEv): m_pEv(pEv)
{

}

void ClientSession::Init()
{
	RegisterMessageHandler();
}

void ClientSession::AddOneMessage(const std::string &strMessage)
{
	m_msgQueue.PushBack(strMessage);
}

void ClientSession::GetOneMessage(std::string &strMessage)
{
	return m_msgQueue.PopFront(strMessage);
}

void ClientSession::RegisterMessageHandler()
{
	m_netMsgHandler.RegisterMessageInfo(MessagePacket::PlayerLogon, &ClientSession::HandlePlayerLogon);
}

void ClientSession::HandleMessage()
{
	std::string strMessage;
	GetOneMessage(strMessage);

	MessagePacket messagePacket;
	messagePacket.ParseFromString(strMessage);

	NetMsgHandler<ClientSession>::NETMSGHANDLE handle = m_netMsgHandler.GetMessageHandler(messagePacket.type());

	if (handle == NULL)
	{
		LWARNING << "Net message handler not found";
		return;
	}
	(this->*handle)(messagePacket.msg());
}

int ClientSession::HandlePlayerLogon(const std::string &strMessage)
{
	//std::string strPtrBuf;
	//strPtrBuf.insert(strPtrBuf.end(), strMessage.begin(), strMessage.begin() + sizeof(void *));

	//ClientSession *pClientSession = NULL;
	//memcpy_s(&pClientSession, sizeof(pClientSession), strPtrBuf.data(), strPtrBuf.size());


	//std::string strLogonMessage;
	//strLogonMessage.insert(strLogonMessage.begin(), strMessage.begin() + sizeof(void *), strMessage.end());

	//MC_PlayerLogon mcPlayerLogon;
	//mcPlayerLogon.ParseFromString(strLogonMessage);



	MC_PlayerLogon mcPlayerLogon;
	mcPlayerLogon.ParseFromString(strMessage);

	std::string strPlayerId;

	if (mcPlayerLogon.is_register())
	{
		strPlayerId = PlayerManager::getInstance().AddPlayer(mcPlayerLogon.name(), mcPlayerLogon.pwd());
	}
	else
	{
		PlayerInfo playerInfo;
		int nRet = PlayerManager::getInstance().GetPlayer(mcPlayerLogon.name(), playerInfo);
		if (nRet != 0)
		{
			LERROR << "Player not exist";
			return nRet;
		}
		strPlayerId = playerInfo.id();
		
	}

	SetPlayerId(strPlayerId);

	int nRet = -1;

	ScriptManager::getInstance().CallScriptFunction("HandlePlayerLogon", "sss>i",
		mcPlayerLogon.name().c_str(), mcPlayerLogon.pwd().c_str(), strPlayerId.c_str(), &nRet);


	//m_mapPlayerIdToClientSession[strPlayerId] = pClientSession;

	return 0;
}
